let currentView = "";

function showForm(title, fieldsHTML) {
    document.getElementById("form-title").innerText = title;
    document.getElementById("form-fields").innerHTML = fieldsHTML;
    document.getElementById("form-popup").style.display = "block";
}

function closeForm() {
    document.getElementById("form-popup").style.display = "none";
}

// 加载用户信息
function loadUsers() {
    currentView = "user";
    fetch("/get_users/")
        .then(response => response.json())
        .then(data => {
            let tableHTML = `
                <h2>用户信息</h2>
                <button onclick="prepareAddUserForm()">添加用户</button>
                <table>
                    <tr>
                        <th>ID</th>
                        <th>用户名</th>
                        <th>邮箱</th>
                        <th>角色</th>
                        <th>操作</th>
                    </tr>
            `;
            data.data.forEach(user => {
                tableHTML += `
                    <tr>
                        <td>${user.id}</td>
                        <td>${user.username}</td>
                        <td>${user.email}</td>
                        <td>${user.role}</td>
                        <td>
                            <button onclick="editUser(${user.id})">编辑</button>
                            <button onclick="deleteUser(${user.id})">删除</button>
                        </td>
                    </tr>
                `;
            });
            tableHTML += `</table>`;
            document.getElementById("content").innerHTML = tableHTML;
        });
}

function prepareAddUserForm() {
    const fields = `
        <input type="text" name="username" placeholder="用户名" required>
        <input type="email" name="email" placeholder="邮箱" required>
        <select name="role" required>
            <option value="admin">管理员</option>
            <option value="planter">种植员</option>
            <option value="inspector">检测员</option>
        </select>
        <input type="password" name="password" placeholder="密码" required>
    `;
    showForm("添加用户", fields);
    document.getElementById("edit-form").onsubmit = addUser;
}

function addUser(event) {
    event.preventDefault();
    const csrfToken = document.querySelector("[name=csrfmiddlewaretoken]").value;
    const formData = new FormData(event.target);
    const data = Object.fromEntries(formData.entries());

    fetch("/add_user/", {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            "X-CSRFToken": csrfToken
        },
        body: JSON.stringify(data)
    }).then(() => {
        closeForm();
        loadUsers();
    });
}

function editUser(id) {
    fetch(`/get_user/${id}/`)
        .then(response => response.json())
        .then(user => {
            const fields = `
                <input type="text" name="username" value="${user.username}" required>
                <input type="email" name="email" value="${user.email}" required>
                <select name="role" required>
                    <option value="admin" ${user.role === "admin" ? "selected" : ""}>管理员</option>
                    <option value="planter" ${user.role === "planter" ? "selected" : ""}>种植员</option>
                    <option value="inspector" ${user.role === "inspector" ? "selected" : ""}>检测员</option>
                </select>
            `;
            showForm("编辑用户", fields);
            document.getElementById("edit-form").onsubmit = function(event) {
                event.preventDefault();
                updateUser(id);
            };
        });
}

function updateUser(id) {
    const csrfToken = document.querySelector("[name=csrfmiddlewaretoken]").value;
    const formData = new FormData(document.getElementById("edit-form"));
    const data = Object.fromEntries(formData.entries());

    fetch(`/update_user/${id}/`, {
        method: "PUT",
        headers: {
            "Content-Type": "application/json",
            "X-CSRFToken": csrfToken
        },
        body: JSON.stringify(data)
    }).then(() => {
        closeForm();
        loadUsers();
    });
}

function deleteUser(id) {
    const csrfToken = document.querySelector("[name=csrfmiddlewaretoken]").value;

    fetch(`/delete_user/${id}/`, {
        method: "DELETE",
        headers: { "X-CSRFToken": csrfToken }
    }).then(() => loadUsers());
}

// 加载作物信息
function loadCrops() {
    currentView = "crop";
    fetch("/get_crops/")
        .then(response => response.json())
        .then(data => {
            let tableHTML = `
                <h2>作物信息</h2>
                <button onclick="prepareAddCropForm()">添加作物</button>
                <table>
                    <tr>
                        <th>ID</th>
                        <th>名称</th>
                        <th>类型</th>
                        <th>种植日期</th>
                        <th>位置</th>
                        <th>操作</th>
                    </tr>
            `;
            data.data.forEach(crop => {
                tableHTML += `
                    <tr>
                        <td>${crop.id}</td>
                        <td>${crop.name}</td>
                        <td>${crop.crop_type}</td>
                        <td>${crop.planting_date}</td>
                        <td>${crop.location}</td>
                        <td>
                            <button onclick="editCrop(${crop.id})">编辑</button>
                            <button onclick="deleteCrop(${crop.id})">删除</button>
                        </td>
                    </tr>
                `;
            });
            tableHTML += `</table>`;
            document.getElementById("content").innerHTML = tableHTML;
        });
}

function prepareAddCropForm() {
    const fields = `
        <input type="text" name="name" placeholder="名称" required>
        <input type="text" name="crop_type" placeholder="类型" required>
        <input type="date" name="planting_date" placeholder="种植日期" required>
        <input type="text" name="location" placeholder="位置" required>
    `;
    showForm("添加作物", fields);
    document.getElementById("edit-form").onsubmit = addCrop;
}

function addCrop(event) {
    event.preventDefault();
    const csrfToken = document.querySelector("[name=csrfmiddlewaretoken]").value;
    const formData = new FormData(event.target);
    const data = Object.fromEntries(formData.entries());

    fetch("/add_crop/", {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            "X-CSRFToken": csrfToken
        },
        body: JSON.stringify(data)
    }).then(() => {
        closeForm();
        loadCrops();
    });
}

function editCrop(id) {
    fetch(`/get_crop/${id}/`)
        .then(response => response.json())
        .then(crop => {
            const fields = `
                <input type="text" name="name" value="${crop.name}" required>
                <input type="text" name="crop_type" value="${crop.crop_type}" required>
                <input type="date" name="planting_date" value="${crop.planting_date}" required>
                <input type="text" name="location" value="${crop.location}" required>
            `;
            showForm("编辑作物", fields);
            document.getElementById("edit-form").onsubmit = function(event) {
                event.preventDefault();
                updateCrop(id);
            };
        });
}

function updateCrop(id) {
    const csrfToken = document.querySelector("[name=csrfmiddlewaretoken]").value;
    const formData = new FormData(document.getElementById("edit-form"));
    const data = Object.fromEntries(formData.entries());

    fetch(`/update_crop/${id}/`, {
        method: "PUT",
        headers: {
            "Content-Type": "application/json",
            "X-CSRFToken": csrfToken
        },
        body: JSON.stringify(data)
    }).then(() => {
        closeForm();
        loadCrops();
    });
}

function deleteCrop(id) {
    const csrfToken = document.querySelector("[name=csrfmiddlewaretoken]").value;

    fetch(`/delete_crop/${id}/`, {
        method: "DELETE",
        headers: { "X-CSRFToken": csrfToken }
    }).then(() => loadCrops());
}

// 按此模式实现 Logs、Pests、Inspections 的增删改查。

// 默认加载作物信息
window.onload = function() {
    loadCrops();
};

function loadLogs() {
    currentView = "log";
    fetch("/get_logs/")
        .then(response => response.json())
        .then(data => {
            let tableHTML = `
                <h2>日志信息</h2>
                <button onclick="prepareAddLogForm()">添加日志</button>
                <table>
                    <tr>
                        <th>ID</th>
                        <th>种植日期</th>
                        <th>数量</th>
                        <th>位置</th>
                        <th>作物名称</th>
                        <th>操作</th>
                    </tr>
            `;
            data.data.forEach(log => {
                tableHTML += `
                    <tr>
                        <td>${log.id}</td>
                        <td>${log.planting_date}</td>
                        <td>${log.quantity}</td>
                        <td>${log.location}</td>
                        <td>${log.crop__name}</td>
                        <td>
                            <button onclick="editLog(${log.id})">编辑</button>
                            <button onclick="deleteLog(${log.id})">删除</button>
                        </td>
                    </tr>
                `;
            });
            tableHTML += `</table>`;
            document.getElementById("content").innerHTML = tableHTML;
        });
}

function prepareAddLogForm() {
    const fields = `
        <input type="date" name="planting_date" placeholder="种植日期" required>
        <input type="number" name="quantity" placeholder="数量" required>
        <input type="text" name="location" placeholder="位置" required>
        <input type="number" name="crop" placeholder="作物ID" required>
    `;
    showForm("添加日志", fields);
    document.getElementById("edit-form").onsubmit = addLog;
}

function addLog(event) {
    event.preventDefault();
    const csrfToken = document.querySelector("[name=csrfmiddlewaretoken]").value;
    const formData = new FormData(event.target);
    const data = Object.fromEntries(formData.entries());

    fetch("/add_log/", {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            "X-CSRFToken": csrfToken
        },
        body: JSON.stringify(data)
    }).then(() => {
        closeForm();
        loadLogs();
    });
}

function editLog(id) {
    fetch(`/get_log/${id}/`)
        .then(response => response.json())
        .then(log => {
            const fields = `
                <input type="date" name="planting_date" value="${log.planting_date}" required>
                <input type="number" name="quantity" value="${log.quantity}" required>
                <input type="text" name="location" value="${log.location}" required>
                <input type="number" name="crop" value="${log.crop}" required>
            `;
            showForm("编辑日志", fields);
            document.getElementById("edit-form").onsubmit = function(event) {
                event.preventDefault();
                updateLog(id);
            };
        });
}

function updateLog(id) {
    const csrfToken = document.querySelector("[name=csrfmiddlewaretoken]").value;
    const formData = new FormData(document.getElementById("edit-form"));
    const data = Object.fromEntries(formData.entries());

    fetch(`/update_log/${id}/`, {
        method: "PUT",
        headers: {
            "Content-Type": "application/json",
            "X-CSRFToken": csrfToken
        },
        body: JSON.stringify(data)
    }).then(() => {
        closeForm();
        loadLogs();
    });
}

function deleteLog(id) {
    const csrfToken = document.querySelector("[name=csrfmiddlewaretoken]").value;

    fetch(`/delete_log/${id}/`, {
        method: "DELETE",
        headers: { "X-CSRFToken": csrfToken }
    }).then(() => loadLogs());
}

function loadPests() {
    currentView = "pest";
    fetch("/get_pests/")
        .then(response => response.json())
        .then(data => {
            let tableHTML = `
                <h2>害虫信息</h2>
                <button onclick="prepareAddPestForm()">添加害虫信息</button>
                <table>
                    <tr>
                        <th>ID</th>
                        <th>害虫类型</th>
                        <th>成因</th>
                        <th>解决方案</th>
                        <th>操作</th>
                    </tr>
            `;
            data.data.forEach(pest => {
                tableHTML += `
                    <tr>
                        <td>${pest.id}</td>
                        <td>${pest.pest_type}</td>
                        <td>${pest.cause}</td>
                        <td>${pest.solution}</td>
                        <td>
                            <button onclick="editPest(${pest.id})">编辑</button>
                            <button onclick="deletePest(${pest.id})">删除</button>
                        </td>
                    </tr>
                `;
            });
            tableHTML += `</table>`;
            document.getElementById("content").innerHTML = tableHTML;
        });
}

function prepareAddPestForm() {
    const fields = `
        <input type="text" name="pest_type" placeholder="害虫类型" required>
        <textarea name="cause" placeholder="成因" required></textarea>
        <textarea name="solution" placeholder="解决方案" required></textarea>
    `;
    showForm("添加害虫信息", fields);
    document.getElementById("edit-form").onsubmit = addPest;
}

function addPest(event) {
    event.preventDefault();
    const csrfToken = document.querySelector("[name=csrfmiddlewaretoken]").value;
    const formData = new FormData(event.target);
    const data = Object.fromEntries(formData.entries());

    fetch("/add_pest/", {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            "X-CSRFToken": csrfToken
        },
        body: JSON.stringify(data)
    }).then(() => {
        closeForm();
        loadPests();
    });
}

function editPest(id) {
    fetch(`/get_pest/${id}/`)
        .then(response => response.json())
        .then(pest => {
            const fields = `
                <input type="text" name="pest_type" value="${pest.pest_type}" required>
                <textarea name="cause" required>${pest.cause}</textarea>
                <textarea name="solution" required>${pest.solution}</textarea>
            `;
            showForm("编辑害虫信息", fields);
            document.getElementById("edit-form").onsubmit = function(event) {
                event.preventDefault();
                updatePest(id);
            };
        });
}

function updatePest(id) {
    const csrfToken = document.querySelector("[name=csrfmiddlewaretoken]").value;
    const formData = new FormData(document.getElementById("edit-form"));
    const data = Object.fromEntries(formData.entries());

    fetch(`/update_pest/${id}/`, {
        method: "PUT",
        headers: {
            "Content-Type": "application/json",
            "X-CSRFToken": csrfToken
        },
        body: JSON.stringify(data)
    }).then(() => {
        closeForm();
        loadPests();
    });
}

function deletePest(id) {
    const csrfToken = document.querySelector("[name=csrfmiddlewaretoken]").value;

    fetch(`/delete_pest/${id}/`, {
        method: "DELETE",
        headers: { "X-CSRFToken": csrfToken }
    }).then(() => loadPests());
}

function loadInspections() {
    currentView = "inspection";
    fetch("/get_inspections/")
        .then(response => response.json())
        .then(data => {
            let tableHTML = `
                <h2>检测记录</h2>
                <button onclick="prepareAddInspectionForm()">添加检测记录</button>
                <table>
                    <tr>
                        <th>ID</th>
                        <th>检测日期</th>
                        <th>检测类型</th>
                        <th>结果</th>
                        <th>作物名称</th>
                        <th>检测员</th>
                        <th>操作</th>
                    </tr>
            `;
            data.data.forEach(record => {
                tableHTML += `
                    <tr>
                        <td>${record.id}</td>
                        <td>${record.inspection_date}</td>
                        <td>${record.inspection_type}</td>
                        <td>${record.result}</td>
                        <td>${record.crop__name}</td>
                        <td>${record.inspector__user__username}</td>
                        <td>
                            <button onclick="editInspection(${record.id})">编辑</button>
                            <button onclick="deleteInspection(${record.id})">删除</button>
                        </td>
                    </tr>
                `;
            });
            tableHTML += `</table>`;
            document.getElementById("content").innerHTML = tableHTML;
        });
}

function prepareAddInspectionForm() {
    const fields = `
        <input type="date" name="inspection_date" placeholder="检测日期" required>
        <input type="text" name="inspection_type" placeholder="检测类型" required>
        <textarea name="result" placeholder="结果" required></textarea>
        <input type="number" name="crop" placeholder="作物ID" required>
        <input type="number" name="inspector" placeholder="检测员ID" required>
    `;
    showForm("添加检测记录", fields);
    document.getElementById("edit-form").onsubmit = addInspection;
}

function addInspection(event) {
    event.preventDefault();
    const csrfToken = document.querySelector("[name=csrfmiddlewaretoken]").value;
    const formData = new FormData(event.target);
    const data = Object.fromEntries(formData.entries());

    fetch("/add_inspection/", {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            "X-CSRFToken": csrfToken
        },
        body: JSON.stringify(data)
    }).then(() => {
        closeForm();
        loadInspections();
    });
}

function editInspection(id) {
    fetch(`/get_inspection/${id}/`)
        .then(response => response.json())
        .then(record => {
            const fields = `
                <input type="date" name="inspection_date" value="${record.inspection_date}" required>
                <input type="text" name="inspection_type" value="${record.inspection_type}" required>
                <textarea name="result" required>${record.result}</textarea>
                <input type="number" name="crop" value="${record.crop}" required>
                <input type="number" name="inspector" value="${record.inspector}" required>
            `;
            showForm("编辑检测记录", fields);
            document.getElementById("edit-form").onsubmit = function(event) {
                event.preventDefault();
                updateInspection(id);
            };
        });
}

function updateInspection(id) {
    const csrfToken = document.querySelector("[name=csrfmiddlewaretoken]").value;
    const formData = new FormData(document.getElementById("edit-form"));
    const data = Object.fromEntries(formData.entries());

    fetch(`/update_inspection/${id}/`, {
        method: "PUT",
        headers: {
            "Content-Type": "application/json",
            "X-CSRFToken": csrfToken
        },
        body: JSON.stringify(data)
    }).then(() => {
        closeForm();
        loadInspections();
    });
}

function deleteInspection(id) {
    const csrfToken = document.querySelector("[name=csrfmiddlewaretoken]").value;

    fetch(`/delete_inspection/${id}/`, {
        method: "DELETE",
        headers: { "X-CSRFToken": csrfToken }
    }).then(() => loadInspections());
}
